var _RDFSource_XMLParser = Components.classes["@mozilla.org/rdf/xml-parser;1"].getService().QueryInterface(Components.interfaces.nsIRDFXMLParser);
var _RDFSource_rdfService = Components.classes["@mozilla.org/rdf/rdf-service;1"].getService(Components.interfaces.nsIRDFService);

function RDFSource(database) {
   this.source = database ? database : Components.classes["@mozilla.org/rdf/datasource;1?name=composite-datasource"].createInstance().QueryInterface(Components.interfaces.nsIRDFCompositeDataSource);
   this.sourcelist = {};
}

RDFSource.prototype._createDataSource = function() {
   return Components.classes["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].createInstance().QueryInterface(Components.interfaces.nsIRDFDataSource);
}

RDFSource.prototype.replaceSubject = function(subject,str, url)
{
   if (!url) {
      url = subject;
   }
   var datasource = this._createDataSource();
   var ioService=Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
   _RDFSource_XMLParser.parseString(datasource,ioService.newURI(url,null,null),str);
   var toRemove = null;
   if (this.sourcelist[subject]) {
      toRemove = this.sourcelist[subject];
   }
   this.sourcelist[subject] = datasource;
   this.source.AddDataSource(datasource);
   if (toRemove) {
      this.source.RemoveDataSource(toRemove);
   }
}

RDFSource.prototype.removeResource = function(subject,source,target) {
   var datasource = this.sourcelist[subject];
   alert("Removing "+target+" from "+source+" in "+subject);
   var sourceResource = _RDFSource_rdfService.GetResource(source);
   var targetResource = _RDFSource_rdfService.GetResource(target);

   var container = Components.classes["@mozilla.org/rdf/container;1"].createInstance(Components.interfaces.nsIRDFContainer);
   container.Init(datasource, sourceResource);
   container.RemoveElement(targetResource,true);
}

RDFSource.prototype.replaceSubjectFromDocument = function(subject,rdfDocument) {
   var serializer = new XMLSerializer();
   var rdfLiteral = serializer.serializeToString(rdfDocument);
   this.replaceSubject(subject,rdfLiteral,null);
}

RDFSource.prototype.removeSubject = function(subject) {
   var datasource = this.sourcelist[subject];
   delete this.sourcelist[subject];
   this.source.RemoveDataSource(datasource);
}

RDFSource.prototype.clear = function() {
   for (subject in this.sourcelist) {
      this.source.RemoveDataSource(this.sourcelist[subject]);
      delete this.sourcelist[subject];
   }
}

